package com.github.mall.common.handler;

import com.github.mall.common.config.JwtPropConfig;
import com.github.mall.common.config.SpringContextHolder;
import com.github.mall.common.util.JwtTokenUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.web.filter.GenericFilterBean;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * JWT登录授权过滤器
 * Created by macro on 2018/4/26.
 */


@Slf4j
@Configuration
public class JwtAuthenticationTokenFilter extends GenericFilterBean {
//    @Autowired
//    private  UserDetailsService userDetailsService;
//    @Autowired
//    private JwtPropConfig jwtPropConfig;

//    @Override
//    protected void doFilterInternal(HttpServletRequest request,
//                                    HttpServletResponse response,
//                                    FilterChain chain) throws ServletException, IOException {
//        String authHeader = request.getHeader(jwtPropConfig.getTokenHeader());
//        if (authHeader != null && authHeader.startsWith(jwtPropConfig.getTokenHead())) {
//            String authToken = authHeader.substring(jwtPropConfig.getTokenHead().length());// The part after "Bearer "
//            String username = JwtTokenUtil.getUserNameFromToken(authToken);
//            logger.info("checking username:{"+username+"}");
//            if (username != null && SecurityContextHolder.getContext().getAuthentication() == null) {
//                UserDetails userDetails = userDetailsService.loadUserByUsername(username);
//                if (JwtTokenUtil.validateToken(authToken, userDetails)) {
//                    UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
//                    authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
//                    logger.info("authenticated user:{"+username+"}");
//                    SecurityContextHolder.getContext().setAuthentication(authentication);
//                }
//            }
//        }
//        chain.doFilter(request, response);
//    }


    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        UserDetailsService userDetailsService = SpringContextHolder.getBean(UserDetailsService.class);
        JwtPropConfig jwtPropConfig = SpringContextHolder.getBean(JwtPropConfig.class);
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        String authHeader = request.getHeader(jwtPropConfig.getTokenHeader());
        if (authHeader != null && authHeader.startsWith(jwtPropConfig.getTokenHead())) {
            String authToken = authHeader.substring(jwtPropConfig.getTokenHead().length());// The part after "Bearer "
            String username = JwtTokenUtil.getUserNameFromToken(authToken);
            logger.info("checking username:{"+username+"}");
            if (username != null && SecurityContextHolder.getContext().getAuthentication() == null) {
                UserDetails userDetails = userDetailsService.loadUserByUsername(username);
                if (JwtTokenUtil.validateToken(authToken, userDetails)) {
                    UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
                    authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
                    logger.info("authenticated user:{"+username+"}");
                    SecurityContextHolder.getContext().setAuthentication(authentication);
                }
            }
        }
        filterChain.doFilter(servletRequest, servletResponse);
    }
}
